package com.cryptape.cita_wallet.fragment.wallet

import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.widget.RelativeLayout
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.MapUtils
import com.cryptape.cita_wallet.CytonApplication
import com.cryptape.cita_wallet.activity.AddWalletActivity
import com.cryptape.cita_wallet.activity.SimpleWebActivity
import com.cryptape.cita_wallet.activity.addtoken.AddTokenActivity
import com.cryptape.cita_wallet.activity.changewallet.ChangeWalletActivity
import com.cryptape.cita_wallet.bean.AddDataItem
import com.cryptape.cita_wallet.constant.ConstantUtil
import com.cryptape.cita_wallet.event.*
import com.cryptape.cita_wallet.fragment.NBaseFragment
import com.cryptape.cita_wallet.item.Token
import com.cryptape.cita_wallet.item.Wallet
import com.cryptape.cita_wallet.language.LanguageType
import com.cryptape.cita_wallet.language.MultiLanguageUtil
import com.cryptape.cita_wallet.net.request.HttpRequestMode
import com.cryptape.cita_wallet.service.ContractService
import com.cryptape.cita_wallet.util.CurrencyUtil
import com.cryptape.cita_wallet.util.RSAUtils
import com.cryptape.cita_wallet.util.db.DBWalletUtil
import com.cryptape.cita_wallet.view.AddDataPopupWindow
import com.cryptape.cita_wallet.view.TitleBar
import com.cryptape.cita_wallet.view.WalletAssetsView
import com.mangoworld.android.R
import kotlinx.android.synthetic.main.custom_titlebar.view.*
import kotlinx.android.synthetic.main.fragment_wallet.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import rx.Observable
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

/**
 * Created by BaojunCZ on 2018/11/19.
 */
class WalletFragment : NBaseFragment(), View.OnClickListener {

    companion object {
        val TAG = WalletFragment::class.java.name!!
    }

    private var mWalletAssetsView: WalletAssetsView? = null
    private var mTitleBar: TitleBar? = null
    private var mRlMessageNote: RelativeLayout? = null;

    private var mTokenItemList: MutableList<Token> = mutableListOf()
    private lateinit var mAdapter: WalletTokenAdapter
    private lateinit var mCircleAnim: Animation

    override val contentLayout: Int
        get() = R.layout.fragment_wallet

    override fun initView() {
        mWalletAssetsView = findViewById(R.id.view_wallet_assets) as WalletAssetsView
        mTitleBar = findViewById(R.id.title) as TitleBar

        mRlMessageNote = findViewById(R.id.rl_message_note) as RelativeLayout
    }

    override fun initData() {
        updateContract()
        loadExchangeBtn()
        recycler.layoutManager = LinearLayoutManager(activity)
        recycler.isNestedScrollingEnabled = false
        reloadTokens()
    }

    override fun initAction() {
        iv_right_arrow.setOnClickListener(this)
        tv_add_token.setOnClickListener(this)
        iv_refresh.setOnClickListener(this)
        mTitleBar!!.setOnRightClickListener {
            var data: List<AddDataItem> = ArrayList<AddDataItem>();

            var popupWindow = AddDataPopupWindow(activity, data);
            popupWindow.showAsDropDown(mTitleBar!!.title_bar_right, 0, 10);
        }
        mTitleBar!!.setOnLeftClickListener {
            if (DBWalletUtil.getAllWallet(activity).size >= 1) {
                activity!!.startActivity(Intent(activity, ChangeWalletActivity::class.java))
                activity!!.overridePendingTransition(R.anim.wallet_activity_in, 0)
            } else {
                activity!!.startActivity(Intent(context, AddWalletActivity::class.java))
            }
//            activity!!.startActivity(Intent(context, CloudMinerActivity::class.java))
        }
        swipe_refresh_layout.setOnRefreshListener {
            iv_refresh.visibility = View.GONE
            //这里获取数据的逻辑
            refreshTokens(false)
            swipe_refresh_layout.isRefreshing = false;

        }

        mRlMessageNote!!.setOnClickListener {
            var url = "https://www.mangoworld.io/lang.php?lang=cn&url=cover-8.html";

            if (MultiLanguageUtil.getInstance().languageType == LanguageType.LANGUAGE_EN) {
                url = "https://www.mangoworld.io/lang.php?lang=en&url=cover-8.html";
            } else if (MultiLanguageUtil.getInstance().languageType == LanguageType.LANGUAGE_JAPAN) {
                url = "https://www.mangoworld.io/lang.php?lang=ja&url=cover-8.html";
            } else if (MultiLanguageUtil.getInstance().languageType == LanguageType.LANGUAGE_KO) {
                url = "https://www.mangoworld.io/lang.php?lang=ko&url=cover-8.html";
            }
            SimpleWebActivity.gotoSimpleWeb(activity, url);

//            activity!!.startActivity(Intent(context, MessageListActivity::class.java))
        }
    }

    //reload list after exchanging wallet
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onWalletSaveEvent(event: TokenRefreshEvent) {
        var status: String = ""
        updateContract()
        if (event != null) {
            if (event.type != null) {
                if (event.address != null) {
                    if (event.type == 1) {
                        status = "0"
                    } else if (event.type == 2) {
                        status = "1"
                    }

                    try {
                        val params: MutableMap<String, String> = MapUtils.newHashMap<String, String>()
                        params["address"] = event.address
                        params["registrationId"] = CytonApplication.getInstance().registrationid
                        params["status"] = status
                        params["type"] = "1"
                        val jsonData = GsonUtils.toJson(params)
                        val content = RSAUtils.encrypt(jsonData)
                        HttpRequestMode.getBindRegistration(activity, content, false)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }
        loadExchangeBtn()
        reloadTokens()
    }

    //refresh list after adding token
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAddTokenEvent(event: AddTokenRefreshEvent) {
        reloadTokens()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCurrencyRefreshEvent(event: CurrencyRefreshEvent) {
        mWalletAssetsView!!.setCurrency()
        mWalletAssetsView!!.setTotalAssets(resources.getString(R.string.wallet_assets_start_query))
        reloadTokens()
    }

    //Subscribe token balance and price
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTokenBalaceEvent(event: TokenBalanceEvent) {
        var isLoadedAll = true
        var totalAssets = 0.0
        mTokenItemList.forEachIndexed { index, item ->
            if (event.item.contractAddress == item.contractAddress && event.item.chainId == item.chainId
                    && event.item.name == item.name && event.item.symbol == item.symbol) {
                mTokenItemList[index] = event.item
                mTokenItemList[index].loaded = true
                totalAssets += event.item.currencyPrice
            } else {
                if (!item.loaded) isLoadedAll = false
            }
            totalAssets += item.currencyPrice
            if (totalAssets != 0.0) {
                mWalletAssetsView!!.setTotalAssets("≈" + CurrencyUtil.getCurrencyItem(context).symbol
                        + " " + CurrencyUtil.formatCurrency(totalAssets))
            }
        }
        if (isLoadedAll) {
            finishRefresh()
            if (totalAssets == 0.0) mWalletAssetsView!!.setTotalAssets(resources.getString(R.string.wallet_token_no_assets))
        }
    }

    override fun onClick(view: View?) {
        when (view!!.id) {
            R.id.iv_right_arrow, R.id.tv_add_token -> startActivity(Intent(activity, AddTokenActivity::class.java))
            R.id.iv_refresh -> {
                if (swipe_refresh_layout.isEnabled)
                    refreshTokens(true)
            }
        }
    }

    private fun getMyTokens(mWallet: Wallet?) {
        var list = mWallet!!.tokens

        if (mWallet != null) {
            mWalletAssetsView!!.setAddress(mWallet.address);
            mWalletAssetsView!!.setName(mWallet.name)
        }
        mTokenItemList.clear()
        list.forEachIndexed { _, tokenItem ->
            if (tokenItem.selected)
                mTokenItemList.add(Token(tokenItem))
        }
        if (mTokenItemList.size == 0) {
            finishRefresh()
            mWalletAssetsView!!.setTotalAssets(resources.getString(R.string.wallet_token_no_assets))
        }
    }

    private fun reloadTokens() {
        startIvRefresh()
        var mWallet = DBWalletUtil.getCurrentWallet(context)
        if (mWallet == null) {
            startActivity(Intent(context, AddWalletActivity::class.java))
            return
        }
        getMyTokens(mWallet)
        mAdapter = WalletTokenAdapter(DBWalletUtil.getCurrentWallet(context).address, mTokenItemList)
        recycler.adapter = mAdapter
    }

    private fun refreshTokens(isIvRefresh: Boolean) {
        if (isIvRefresh) {
            startIvRefresh()
        }
        var mWallet = DBWalletUtil.getCurrentWallet(context)
        if (mWallet == null) {
            startActivity(Intent(context, AddWalletActivity::class.java))
            return
        }
        getMyTokens(mWallet)
        EventBus.getDefault().post(QueryMIDEvent());
        mAdapter.refresh(mTokenItemList)
    }

    //iv_refresh animation
    private fun startIvRefresh() {
        swipe_refresh_layout.isEnabled = false
        mCircleAnim = AnimationUtils.loadAnimation(context, R.anim.anim_round_rotate)
        val interpolator = LinearInterpolator()
        mCircleAnim.interpolator = interpolator
        iv_refresh.startAnimation(mCircleAnim)
    }

    private fun finishRefresh() {
        swipe_refresh_layout.isRefreshing = false
        swipe_refresh_layout.isEnabled = true
        iv_refresh.clearAnimation()
        iv_refresh.visibility = View.VISIBLE
    }

    private fun loadExchangeBtn() {
//        if (DBWalletUtil.getAllWalletName(activity!!).size > 1) {
//            mTitleBar!!.setRightImage(R.drawable.ic_wallet_exchange)
//        } else {
//            mTitleBar!!.setRightImage(R.drawable.ic_wallet_rec_add)
//        }
        mTitleBar!!.setRightImage(R.drawable.icon_add)
    }


    private fun updateContract() {
        showProgressBar()
        Observable.fromCallable {
            val datas = ContractService.updateContract()
            datas
        }.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(object : Subscriber<String>() {
                    override fun onCompleted() {
                        dismissProgressBar()
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressBar()
                    }

                    override fun onNext(result: String) {
                        dismissProgressBar()
                        LogUtils.dTag("MainActivity==", "result = " + result + " contract = " + ConstantUtil.getDEPOSITCONTRACT())
                    }
                })
//                        Subscriber<List<Type>>() {
//                    override fun onCompleted() {
//                        dismissProgressBar()
//                    }
//
//                    override fun onError(e: Throwable) {
//                        dismissProgressBar()
//                    }
//
//                    fun onNext(types: List<Type>) {
//                        dismissProgressBar()
//                        LogUtils.dTag("MainActivity==", "contract = " + ConstantUtil.getDEPOSITCONTRACT())
//                    }
//                })
    }

//    fun getVGrade() {
//        TokenService.getVGrade().subscribe(object : Subscriber<VStimulateBean?>() {
//            override fun onCompleted() {}
//            override fun onError(e: Throwable) {}
//            override fun onNext(vStimulateBean: VStimulateBean?) {
//                if (vStimulateBean!!.code == 0) {
//                    CytonApplication.getInstance().VStimulate = vStimulateBean!!.data
//                    if (SettingsFragment.mMyVStimulate != null)
//                        SettingsFragment.mMyVStimulate.visibility = if (vStimulateBean!!.data <= 0) View.GONE else View.VISIBLE
//                }
//            }
//        })
//    }
}